package com.miyake.server.servlet;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

import com.miyake.client.datamanage.Data;
import com.miyake.client.datamanage.PlotData;
import com.miyake.server.DsData;
import com.miyake.server.dsaccess.NodeManager;

public class StoreCSV {

	public StoreCSV(BufferedInputStream bis, String key, String name) {
//		DataInputStream inData = new DataInputStream(bis);
//		BufferedReader reader = new BufferedReader(new InputStreamReader(inData));
		DsData data = new DsData();
		byte[] b = new StoreOriginal(data, bis, key, name).getByte();
	
		data.setParsed(true);
		// Temporary class for multiple column data
		class DataContainer {
			private List<String> data = new LinkedList<String>();
			public List<String> getData() {
				return data;
			}
		}
		List<DataContainer> listData = new ArrayList<DataContainer>();
		
		data.setXmin(0.0);

		String str = new String(b);
		String[] lines = str.split("\n");
		double d = 0.0;
		try { 
			boolean first = true;
			for(int i = 0; i < lines.length; i++) {
				String[] s = lines[i].split(",");
				if (first) {
					for (int j = 0; j < s.length; j++) {
						listData.add(new DataContainer());
					}
					first = false;
				}
				for (int j = 0; j < s.length; j++) {
					listData.get(j).getData().add(s[j]);
				}
				d += 1.0;
			}
			
		}
		catch (Exception e) {
			
		}
		finally {
			data.setXmax(d);
			data.setTitleRow(0);
			if (listData.size() > 1) {
				data.setType(PlotData.DATA_XY);
			}
			else {
				data.setType(PlotData.DATA_Y);
			}
			for (int i = 0; i < listData.size(); i++) {
				data.addData(listData.get(i).getData(), "");
			}
//				inData.close();
			data.setSourceType(Data.SourceTypeFile);
			NodeManager.getInstance().createData(name, key, data, -1);
		}
		
	}

}
